/*
 * @Author: ZhanXie
 * @Date: 2020-05-25 09:25:29
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-08-26 10:50:18
 * @Description: 
 * @FilePath: \next-create\server\controllers\auth.js
 */
const {
  generateToken,
  getUserInfo
} = require('../core/util')
const config = require('../../config')

const { OAUTH_URL } = config
const { userInfoUrl } = config.github

class AuthController {
  static async getToken(ctx) {
    const code = ctx.query.code
    if (!code) {
      ctx.body = 'code not exist'
      return
    }
    // 通过 code, client_id, client_secret 获取 access_token token_type
    const result = await generateToken(code)
    console.log('request_token_url', result)
    // 通过 access_token token_type 获取 用户信息
    if (result.status === 200 && (result.data && !result.data.error)) {
      ctx.session.githubAuth = result.data
      const { access_token, token_type } = result.data
      const userInfoResp = await getUserInfo(userInfoUrl, `${token_type} ${access_token}`)
      console.log('userInfoResp', userInfoResp)
      ctx.session.userInfo = userInfoResp.data
      ctx.redirect((ctx.session && ctx.session.urlBeforeOAuth) || '/')
      ctx.session.urlBeforeOAuth = ''
    } else {
      const errorMsg = result.data && result.data.error
      ctx.body = `request token fail ${errorMsg} `
    }
  }

  static async logout(ctx) {
    ctx.session = null
    ctx.body = 'logout success'
  }

  static async prepareAuth(ctx) {
    const { url } = ctx.query
    ctx.session.urlBeforeOAuth = url
    ctx.redirect(OAUTH_URL)
  }
}
module.exports = AuthController